/*
 * Server.cpp
 *
 *  Created on: 29/05/2011
 *      Author: dela
 */

#include "Server.h"

using namespace std;

/**
 *
 */
void Server::acceptConnections() {
	instructorAccepter.start();
	studentAccepter.start();
}


/**
 *
 */
void Server::serverShutdown() {
	instructorAccepter.stop();
	studentAccepter.stop();

	//Libero cursos y clases:
	if ( courses.size() > 0 ) {
		map<unsigned int, Course*>::iterator it;
		for ( it=courses.begin() ; it != courses.end(); it++ ) {
			delete (*it).second;
		}
	}
	if ( classes.size() > 0 ) {
		map<unsigned int, Class*>::iterator it;
		for ( it=classes.begin() ; it != classes.end(); it++ ) {
			delete (*it).second;
		}
	}

}

/**
 *
 */
bool Server::getUser(std::string userName, User &user) {
	if (userName == "")
		return false;
	ifstream input("users");
	string s = "";
	bool found = false;
	while ( user.getName() != userName && input.good() ) {
		getNextString(input, s);
		user.setType( s.c_str()[0] );
		getNextString(input, s);
		user.setName( s );
		getNextString(input, s);
		user.setPassword( s );
		if (user.getName() == userName)
			found = true;
	}
	input.close();
	return found;
}

/**
 *
 */
void Server::getNextString(ifstream &input, string &s) {
	s.clear();
	char c[2];
	c[1] = '\0';
	*c = input.get();
	while (*c > -1 && *c != '|' && *c != '\n') {
		s.append(c);
		*c = input.get();
	}
	if (s.length() == 0 and *c > -1)
		getNextString(input,s);
}
